package com.my.xq.service.impl;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.my.wechat.controller.WxTemplateMesController;
import com.my.xq.domain.PlanQueryParam;
import com.my.xq.domain.entity.Plan;
import com.my.xq.domain.entity.Plan_Court;
import com.my.xq.domain.entity.RenWu;
import com.my.xq.repository.OptionRepository;
import com.my.xq.repository.PlanRepository;
import com.my.xq.repository.Plan_CourtRepository;
import com.my.xq.repository.RenWuRepository;
import com.my.xq.repository.VoteResultRepository;
import com.sskj.core.annotation.ControllerLogExeTime;
import com.sskj.sys.repository.MediaRepository;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/fatp")
public class PlanServiceImpl {
	@Autowired
	PlanRepository planRepository;
	
	@Autowired
	Plan_CourtRepository plan_CourtRepository;
	
	@Autowired
	OptionRepository optionRepository;
	
	@Autowired
	VoteResultRepository voteResultRepository;
	
	@Autowired
	MediaRepository mediaRepository;
	
	@Autowired
	RenWuRepository rwRepository;
	
	@Autowired
	private WxMpService wxService;
	
	@Value(value="${wechat.mp.voteTempleteCode}")  
    private String voteTempleteCode; 
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/addfatpInfo", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "添加方案投票")
	public void addfatpInfo(Plan p) {
		if(null==p.getId()||"".equals(p.getId())) {
			p.setIsbindCourt(false);	//新增时是没有绑定小区的
			p.setIscreateOption(false);	//新增时还没有建立投票的选项
			p.setPlanState(1);	//新增时默认状态为已经建立没有启用或者停用
		}else {
			Plan plan=planRepository.get(p.getId());
			p.setIsbindCourt(plan.isIsbindCourt());
			p.setIscreateOption(plan.isIscreateOption());
			p.setPlanState(plan.getPlanState());
		}
		planRepository.save(p);
		if (!p.getFiles().isEmpty()) {
			mediaRepository.updateMedia(p.getId(), this.toList(p.getFiles(), ","));
		}

		mediaRepository.delMedia(p.getId(),
				this.toList(p.getFiles().isEmpty() ? "XXXXX" : p.getFiles(), ","));
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/findAll", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "查询方案投票信息")
	@ApiOperation(value = "查询方案投票信息", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "姓名", paramType = "form", dataType = "string"),
		@ApiImplicitParam(name = "pageNumber", value = "页号", paramType = "form", dataType = "int"),
		@ApiImplicitParam(name = "pageSize", value = "页的大小", paramType = "form", dataType = "int") })
	public Page<Plan> findAllPage(@ApiIgnore PlanQueryParam pqp,@ApiIgnore Pageable pageable,HttpServletRequest request) {
		Page<Plan> page = planRepository.findPage(pqp,pageable);
		return page;
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "查询一条方案投票记录", log = false)
	@RequestMapping("/findOne")
	public Plan findOne(String id,HttpServletRequest request) {
		Plan court = planRepository.get(id);
		return court;
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "删除方案投票信息", log = false)
	@RequestMapping("/delfatpInfo")
	public void delyz(String id) {
		planRepository.delete(id);
		mediaRepository.delMedia(id,this.toList("XXXXX", ","));
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "方案绑定小区", log = false)
	@RequestMapping("/bindcourt")
	public void bindcourt(Plan_Court plan_Court) {
		List<String> courtids=this.toList(plan_Court.getCourtid(), ",");
		plan_CourtRepository.unbindCourt(plan_Court.getPlanid());
		for (int i = 0; i < courtids.size(); i++) {
			Plan_Court pc=new Plan_Court();
			pc.setCourtid(courtids.get(i));
			pc.setPlanid(plan_Court.getPlanid());
			plan_CourtRepository.save(pc);
		}
		//绑定完之后去要把对应方案的isbindCourt设置为true
		Plan p=planRepository.get(plan_Court.getPlanid());
		p.setIsbindCourt(true);
		planRepository.save(p);
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "改变方案投票的状态", log = false)
	@RequestMapping("/changePlanState")
	public void changePlanState(Plan plan) {
		planRepository.changePlanState(plan.getPlanState(),plan.getId());
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "方案解绑小区", log = false)
	@RequestMapping("/unbindcourt")
	public void unbindcourt(String id) {
		plan_CourtRepository.unbindCourt(id);
		//解绑完之后去要把对应方案的isbindCourt设置为false
		Plan p=planRepository.get(id);
		p.setIsbindCourt(false);
		planRepository.save(p);
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "根据小区id查询正在进行中的投票方案", log = false)
	@RequestMapping("/findPlanInProcess")
	public List<Plan> findPlanInProcess(String courtid) {
		return planRepository.findPlanInProcess(courtid);
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "根据业主id和投票状态查询投票方案", log = false)
	@RequestMapping("/findPlanByProprietor")
	public List<Plan> findPlanByProprietor(Plan p) {
		return planRepository.findPlanByProprietor(p.getProprietorId(),p.getPlanState());
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "测试发送模板消息", log = false)
	@RequestMapping("/testSendTemplete")
	public void testSendTemplete(Plan p) {
		WxTemplateMesController wmc=new WxTemplateMesController();
		try {
			wxService.getTemplateMsgService().sendTemplateMsg(wmc.getTemplate("ocXRm0xAC1NZBS103ht7Nhq5qruw", "御景天地", "我要报名",
					"2018-01-29", "http://www.baidu.com",voteTempleteCode));
		} catch (WxErrorException e) {
			logger.error("发送模板消息失败");
			e.printStackTrace();
		}
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "测试判断任务发起任务结束任务", log = false)
	@RequestMapping("/testTaskJudge")
	public void testTaskJudge(Plan p) {
		//获取正在执行中的任务
		List<RenWu> rwList=rwRepository.taskFindRenWuActive();
		Date now = new Date(); 
		for (int i = 0; i < rwList.size(); i++) {
			RenWu rw=rwList.get(i);
			Date d=rw.getEndTime();
			int res = now.compareTo(d);
			if(res==1&&rw.isActive()) {	
				//需要结束任务,同时根据层级发起下一层任务
				rw.setActive(false);
				rw.setOver(true);
				if(!rw.getCode().equals("CAST04")) {
					RenWu newRenwu=new RenWu();
					newRenwu.setCourtId(rw.getCourtId());
					if(rw.getCode().equals("CAST01")) {
						newRenwu.setCode("CAST02");
					}
					else if(rw.getCode().equals("CAST02")) {
						newRenwu.setCode("CAST03");
					}
					else if(rw.getCode().equals("CAST03")) {
						newRenwu.setCode("CAST04");
					}
					else {
						logger.error("任务Code错误");
					}
					//更新下一层级任务的状态
					RenWu r=rwRepository.findRenWuByCourtANDCode(newRenwu.getCourtId(),
							newRenwu.getCode());
					r.setStartTime(now);
					Calendar ca = Calendar.getInstance();
					ca.add(Calendar.DATE, 15); // 默认期限为15天
					r.setEndTime(ca.getTime());
					r.setActive(true);
					r.setOver(false);
					rwRepository.save(r);
				}
				rwRepository.save(rw);
			}
		}
	}
	
	public List<String> toList(String value, String separator) {
		List<String> result = new ArrayList<String>();
		if (!this.isEmpty(value)) {
			String[] as = value.split(separator);
			for (int i = 0; i < as.length; i++) {
				result.add(as[i]);
			}
		}
		return result;
	}
	
    public boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
}
